﻿package org.neatmvc.core{
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import org.neatmvc.interfaces.IController;
	import org.neatmvc.utils.ClassUtil;
		
	public class Controller extends EventDispatcher{
		
		private static var controllerMap:Dictionary = new Dictionary();//全局控制器Controller实例缓存池
		
		///////////////////////
		//构造函数
		////////////////////////
		public function Controller(e:Event){//参数不能为空值，每个controller必须有事件来注册！
			var className:String = ClassUtil.nameOf(this);
			if ( controllerMap[className] != null){
				throw new Error("对象只能被实例化一次！");
			}else{
				controllerMap[className] = this;
				this.addEventListener(e.type,this.execute);
			}
			
			this.onRegister( );//执行注册时的附加操作
		}
		
		///////////////////////////////
		//静态方法
		///////////////////////////////////////
		
		//根据类名取回Controller
		public  function getController(key:String):Controller{
			if ( controllerMap[key] == null ) {
				throw new Error("对象'" + key + "' 还未实例化！");
			}else{
				return controllerMap[key];
			}
		}
		
		//注销Controller
		public  function removeController(key:String):Controller {
			var controller:Controller = controllerMap[key] as Controller;
			if (controller) {
				controllerMap[key] = null;
				delete controllerMap[key];
				controller.onRemove();//执行注销时的附加操作
			}
			return controller;
		}
	
		//控制器范围内广播事件
		public static function notifyObsviers(e:Event):void {
			for each (var controller in controllerMap) { 
				if (controller.hasEventListener(e.type) ){
					controller.dispatchEvent(e);
				}
			}
		}
		/////////////////////////////
		//实例方法
		////////////////////////////////////
		
		//需子类覆盖此方法，以执行逻辑处理
		public function execute(e:Event):void{
			trace("Contrller 核心类 - execute方法");
		}
		
		//注册controller时附加操作
		public function onRegister( ):void {
			trace( "注册Controller: " + this );
		}
		
		//注销controller时附加操作
		public function onRemove( ):void {
			trace("注销Controller: "+this);
		}
		
	}
}